import { loadEnv } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import path from 'path';
// import viteCompression from 'vite-plugin-compression';
import { codeInspectorPlugin } from 'code-inspector-plugin';
import uniReadPagesV3Plugin from './sheep/router/utils/uni-read-pages-v3';
import mpliveMainfestPlugin from './sheep/libs/mplive-manifest-plugin';
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from 'weapp-tailwindcss/vite';

import AutoImport from 'unplugin-auto-import/vite';
const resolve = (p) => {
  return path.resolve(__dirname, p);
};

// 注意： 打包成 h5 和 app 都不需要开启插件配置
const isH5 = process.env.UNI_PLATFORM === 'h5';
const isApp = process.env.UNI_PLATFORM === 'app';
const WeappTailwindcssDisabled = isH5 || isApp;

// https://vitejs.dev/config/
export default (command, mode) => {
  const env = loadEnv(mode, __dirname, 'SHOPRO_');
  return {
    build: {
      sourcemap: true, // 或者设为 false 禁用 sourcemap
    },
    envPrefix: 'SHOPRO_',
    plugins: [
      uni(),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        imports: ['vue', 'uni-app'],
        dts: 'typings/auto-imports.d.ts',
      }),
      uvwt({
        // rem2rpx: true,
        disabled: WeappTailwindcssDisabled,
        // 由于 hbuilderx 会改变 process.cwd 所以这里必须传入当前目录的绝对路径
        tailwindcssBasedir: __dirname,
      }),
      codeInspectorPlugin({
        bundler: 'vite',
        hideDomPathAttr: true,
        editor: 'trae',
        showSwitch: true,
      }),
      // viteCompression({
      // 	verbose: false
      // }),
      uniReadPagesV3Plugin({
        pagesJsonDir: path.resolve(__dirname, './pages.json'),
        includes: ['path', 'aliasPath', 'name', 'meta'],
      }),
      mpliveMainfestPlugin(env.SHOPRO_MPLIVE_ON),
    ],
    server: {
      host: true,
      // open: true,
      port: env.SHOPRO_DEV_PORT,
      hmr: {
        overlay: true,
      },
    },
    css: {
      postcss: {
        plugins: [
          require('tailwindcss')({
            // 注意此处，手动传入你 `tailwind.config.js` 的绝对路径
            config: resolve('./tailwind.config.js'),
          }),
          require('autoprefixer'),
        ],
      },
    },
  };
};
